#include "stack.h"


// 创建链式栈
LinkedStack *stack_create() {
	return (LinkedStack *)calloc(1, sizeof(LinkedStack));
}

// 销毁链式栈
void stack_destroy(LinkedStack *stack) {
	if (stack == NULL) {
		return;
	}

	Stack *s = stack->top;
	while (s != NULL) {
		Stack *p = s->next;
		free(s);
		s = p;
	}
	free(stack);
}

// 判空
bool stack_is_empty(const LinkedStack *stack) {
	return stack->top == NULL;
}

// 入栈
void stack_push(LinkedStack *stack, const char *data) {
	Stack *s = (Stack *)calloc(1, sizeof(Stack));
	if (s == NULL) {
		printf("stack_push calloc s error!\n");
		return;
	}

	strcpy(s->data, data);
	s->next = stack->top;

	stack->top = s;
}

// 出栈并返回栈顶元素, 返回-1为空栈
int stack_pop(LinkedStack *stack, char *data) {
	if (stack_is_empty(stack)) {
		return -1;
	}

	Stack *s = stack->top;
    strcpy(data, s->data);
	stack->top = stack->top->next;
	free(s);

	return 1;
}

// 访问栈顶元素
char *stack_peek(const LinkedStack *stack) {
	if (stack_is_empty(stack)) {
		return NULL;
	}

	return stack->top->data;
}
